package com.xm.xmapp.service;

import java.util.HashMap;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

import com.xm.xmapp.R;
import com.xm.xmapp.response.bean.JpushNotifactionResponse;

public class MusicService extends Service {
	private MediaPlayer mp;
	private final HashMap<Integer, Integer> musicDir = new HashMap<Integer, Integer>();

	@Override
	public void onCreate() {
		super.onCreate();// 继承onCreate方法
		try {
			mp = new MediaPlayer();
			musicDir.put(JpushNotifactionResponse.TYPE_VOICE30, R.raw.soc30);
			musicDir.put(JpushNotifactionResponse.TYPE_VOICE15, R.raw.soc15);
			musicDir.put(JpushNotifactionResponse.TYPE_VOICE5, R.raw.soc5);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (intent != null) {
			int type = intent.getIntExtra("type", 0);
			if (type != 0) {
				if (mp.isPlaying()) {
					mp.stop();
					mp.reset();
				}
				mp = MediaPlayer.create(MusicService.this, musicDir.get(type));
				mp.start();
				mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
					public boolean onError(MediaPlayer mp, int what, int extra) {
						// 释放资源
						try {
							mp.release();
						} catch (Exception e) {
							e.printStackTrace();
						}
						return false;
					}
				});
			}
		}
		return super.onStartCommand(intent, Service.START_REDELIVER_INTENT, startId);// 保证intent参数不为空
	}

	@Override
	public void onDestroy() {// 服务停止时停止播放音乐并释放资源
		mp.stop();
		mp.release();
		mp = null;
		super.onDestroy();
	}
}
